package baseclass.z_lruCache;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @date 2020/3/5 18:22
 */
public class Code02_LinkedHashMap_LRU2<K, V> {
    private final int CAPACITY;
    private LinkedHashMap<K, V> cache;
    private static float DEFAULT_LOAD_FACTORY = 0.75f;

    public Code02_LinkedHashMap_LRU2(int CAPACITY) {
        this.CAPACITY = CAPACITY;
        //匿名内部类
        this.cache = new LinkedHashMap<K, V>((int) (CAPACITY / DEFAULT_LOAD_FACTORY) + 1,
                DEFAULT_LOAD_FACTORY, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> entry) {
                return size() > CAPACITY;
            }
        };
    }

    public void put(K k, V v) {
        cache.put(k, v);
    }

    public V get(K k) {
        return cache.get(k);
    }

    public V remove(K k) {
        return cache.remove(k);
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<K, V> entry : cache.entrySet()) {
            sb.append("K:").append(entry.getKey()).append(" V:").append(entry.getValue());
            sb.append("\r\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Code02_LinkedHashMap_LRU2<Integer, String> cache = new Code02_LinkedHashMap_LRU2<>(5);
        for (int i = 1; i <= 5; i++) {
            cache.put(i, " " + i);
            System.out.println(cache);
        }
        System.out.println("插入6");
        cache.put(6, " " + 6);
        System.out.println(cache);
        System.out.println("查询5");
        System.out.println(cache.get(5));
        System.out.println(cache);
        System.out.println("删除2");
        System.out.println(cache.remove(2));
        System.out.println(cache);
        System.out.println("插入2");
        cache.put(2, "2");
        System.out.println(cache);
        System.out.println("查询3");
        System.out.println(cache.get(3));
        System.out.println(cache);


    }


}
